<template>
    <div class="containers">
        <div class="cardContainer">
            <div>{{ groupName }}</div>
            <el-card v-for="(item, index) in videoList" :key="index" class="item">
                <template #header>{{ isGroup?item.stream.split(groupName)[0] :item.stream.split("Time")[0]}}
                    <el-button style="margin-left: 10px;" type="primary" @click="clickPlay(item)" plain>播放</el-button>
                    <el-button style="margin-left: 10px;" type="primary" @click="stop(item)" plain>停止</el-button></template>
                <video ref="videos" :id="item.client_id" controls style="width: 400px;height: 300px;"></video>
            </el-card>
        </div>
    </div>
</template>
<script>
import { onMounted, ref, inject, watch, onUnmounted, nextTick } from 'vue'
import { videoStore } from '@/store/video'
import * as signalR from '@microsoft/signalr';
import { userStore } from '@/store/userStore'
import { SignalrStore } from '@/store/signalrStore'
export default {
    props: {
        currentName: String,
        toUserName: String,
        fromUserName: String,
        isGroup: {
            type: Boolean,
            default: false
        },
        groupName: String
    },
    setup(props) {
        const videoList = ref([]);
        var mapSdk = new Map();
        var mapchatSdk = new Map();
        var userData = ref([]);
        var videos = ref();
        var urlData = null;
        var time=null;
        onUnmounted(() => {

            const videoElements = document.querySelectorAll('video');
            videoElements.forEach(video => {
                video.pause(); // 停止视频播放
                video.removeAttribute('src'); // 清除 src 属性
            });
            videoList.value.forEach(s => {
                stop(s);
            });
            setTimeout(() => {
                mapchatSdk.forEach((value, key) => {

                    console.log('close');
                    value.close();
                    value = null;
                });
            }, 100)
            setTimeout(() => {
                mapSdk.forEach((value, key) => {

                    console.log('close');
                    value.close();
                    value = null;
                });
            }, 100)
        });
        onMounted(async () => {
            try {
                time=new Date().getTime();
                var res = await fetch('/configjs.json?d=' + new Date());
                urlData = await res.json();
                SignalrStore().getSignalrInstance().on("Notity", (datas) => {
                    if (datas && datas.length > 0) {
                        debugger;
                        const videoElements = document.querySelectorAll('video');

                        // 遍历所有的 video 元素并清除其 src 属性
                        videoElements.forEach(video => {
                            if (datas.filter(s => s.client_id == video.id) <= 0) {

                                video.pause(); // 停止视频播放
                                video.removeAttribute('src'); // 清除 src 属性
                            }
                        });
                        videoList.value = datas;
                        datas.forEach(element => {
                            play(element);
                        });
                    }
                });
                if (!props.isGroup) {
                    await push();
                }
                else {
                    await pushCurrent();
                }
            } catch (error) {
                console.error(error);
            }
        });
        const play = (item) => {
            var url = urlData.pullUrl + "app=" + item.app + '&stream=' + item.stream + ".flv";
            var r = apply_url_change(url);
            var sdks = new SrsRtcWhipWhepAsync();
            var video = document.getElementById(item.client_id);
            if (video == null) {
                setTimeout(() => {
                    while (video == null) {
                        video = document.getElementById(item.client_id);
                    }
                    video.srcObject = sdks.stream;
                    sdks.play(r.url, {
                        videoOnly: false,
                        audioOnly: false,
                    })
                        .then(function (session) {
                            video.play()
                            video.muted = false;
                            mapchatSdk.set(item.app, sdks);
                        }).catch(function (reason) {
                            sdks.close();
                            console.error(reason);
                        });
                }, 100)
            }
            // else {
            //     let isFlv = r.stream.indexOf('.flv') > 0;
            //     isFlv = isFlv || r.stream && r.url.indexOf('http') === 0;
            //     if (isFlv) {
            //         if (!mpegts.getFeatureList().mseLivePlayback) {
            //             return;
            //         }
            //         var flvPlayer = mpegts.createPlayer({
            //             type: 'flv', url: r.url,
            //             isLive: true, enableStashBuffer: true, liveSync: true
            //         });
            //         flvPlayer.on('media_info', function () {

            //             setTimeout(() => {
            //                 flvPlayer.play();
            //                 video.play();
            //             }, 200);
            //             //videoElement.play(); // 开始播放视频
            //         });
            //         // flvPlayer.on(mpegts.ErrorTypes.MEDIA_ERROR, function (errorType, data) {
            //         //     console.error('flv.js 渲染失败:', errorType, data);
            //         // });
            //         // flvPlayer.on(mpegts.ErrorTypes.NETWORK_ERROR, function (errorType, data) {
            //         //     console.error('flv.js 渲染失败:', errorType, data);
            //         // });
            //         // flvPlayer.on(mpegts.ErrorTypes.OTHER_ERROR, function (errorType, data) {
            //         //     console.error('flv.js 渲染失败:', errorType, data);
            //         // });
            //         flvPlayer.attachMediaElement(video);
            //         flvPlayer.load();
            //         // setInterval(() => {
            //         //     flvPlayer.load();
            //         //         flvPlayer.play();
            //         //         }, 200);
            //         // setTimeout(() => {
            //         // }, 100);
            //         // video.play();
            //         // video.addEventListener('canplay', function () {

            //         //     flvPlayer.play();
            //         //     setTimeout(() => {
            //         //         // flvPlayer.play();
            //         //         video.play();
            //         //     }, 200);
            //         // });
            //         // flvPlayer.load();
            //         // setTimeout(() => {
            //         //     // 在控制台打印当前时间
            //         //     flvPlayer.play();
            //         // }, 100);
            //         mapFlv.set(item.client_id, flvPlayer);
            //         return;
            //     }
            // }
            //#endregion
        };
        const clickPlay = (item) => {
            var url = urlData.pullUrl + "app=" + item.app + '&stream=' + item.stream + ".flv";
            var r = apply_url_change(url);
            var sdks = new SrsRtcWhipWhepAsync();
            var video = document.getElementById(item.client_id);
            if (video == null) {
                setTimeout(() => {
                    while (video == null) {
                        video = document.getElementById(item.client_id);
                    }

                    video.srcObject = sdks.stream;
                    sdks.play(r.url, {
                        videoOnly: false,
                        audioOnly: false,
                    })
                        .then(function (session) {
                            video.play()
                            video.muted = false;

                            mapchatSdk.set(item.app, sdks);
                        }).catch(function (reason) {
                            sdks.close();
                            console.error(reason);
                        });
                }, 100)
            }
            else {
                video.srcObject = sdks.stream;
                sdks.play(r.url, {
                    videoOnly: false,
                    audioOnly: false,
                })
                    .then(function (session) {
                        video.play()
                        video.muted = false;

                        mapchatSdk.set(item.app, sdks);
                    }).catch(function (reason) {
                        sdks.close();
                        console.error(reason);
                    });
            }
        };
        const stop = (item) => {
            var playSdk = mapchatSdk.get(item.app);
            if (playSdk) {
                playSdk.close();
            }
        };
        var apply_url_change = function (url) {
            var query = parse_query_string();
            var r = parse_rtmp_url(url);
            var url = window.location.protocol + "//" + query.host + query.pathname + "?autostart=true"
                + "&app=" + r.app + "&stream=" + r.stream + "&server=" + r.server + "&port=" + r.port;
            url += (query.shp_identify) ? "&shp_identify=" + query.shp_identify : '';
            url += (r.vhost === "__defaultVhost__") ? "&vhost=" + r.server : "&vhost=" + r.vhost;
            url += (r.schema !== "rtmp") ? "&schema=" + r.schema : '';
            url += (query.buffer) ? "&buffer=" + query.buffer : '';
            url += (query.api_port) ? "&api_port=" + query.api_port : '';

            var queries = user_extra_params(query);
            queries = user_extra_params(r, queries);

            if (queries && queries.length) {
                url += '&' + queries.join('&');
            }

            return r;
        };
        const push = async () => {
            var audio = videoStore().getAudio();
            var video = videoStore().getVideo();
            if (audio != "" || video != "") {
                var sdk = new SrsRtcWhipWhepAsync(video, audio);
                var Finalurl = urlData.pushUrl + 'app=single' + props.currentName + 'And' + props.toUserName + '&stream=' + props.currentName+"Time"+time;
                if (props.fromUserName) {
                    Finalurl = urlData.pushUrl + 'app=single' + props.fromUserName + 'And' + props.currentName + '&stream=' + props.currentName+"Time"+time;
                }
                await sdk.publish(Finalurl);

                mapSdk.set(props.currentName, sdk);
            }
            else {
                if (!props.isGroup) {
                    var shareUser = await fetch(urlData.apiUrl + "/GetSingleChat?Name=" + videoStore().getName()+"Time"+time);
                    var shareModel = await shareUser.json();
                    var notity = await fetch(urlData.apiUrl + "/NoVideoAndAudioNotity?Name=" + videoStore().getName()+"Time"+time);
                    if (shareModel && shareModel.length > 0) {
                        videoList.value = shareModel.filter(s=>s!=null);
                        shareModel.forEach(element => {
                            if (element != null) {
                                play(element);
                            }
                        });
                    }
                }

            }

        }
        const pushCurrent = async () => {
            var current = videoStore().getName();
            var audio = videoStore().getAudio();
            var video = videoStore().getVideo();
            if (audio != "" || video != "") {
                var sdk = new SrsRtcWhipWhepAsync(video, audio);
                var Finalurl = urlData.pushUrl + 'app=group' + props.groupName + '&stream=' + current + props.groupName+"Time"+time;
                await sdk.publish(Finalurl);
                mapSdk.set(props.groupName, sdk);
            }
            else {
                if (props.isGroup) {
                    var shareUser = await fetch(urlData.apiUrl + "/GetGroupByName?Name=" + props.groupName+"Time"+time);
                    var shareModel = await shareUser.json();
                    if (shareModel && shareModel.requestDatas && shareModel.requestDatas.length > 0) {
                        videoList.value = shareModel.requestDatas;
                        shareModel.requestDatas.forEach(element => {
                            play(element);
                        });
                    }
                }

            }
        }
        const calcel = () => {
            if (sdk) {
                sdk.close();
            }
        }
        window.addEventListener('unload', function (event) {
            calcel();
        });
        return {
            videoList,
            play,
            stop, push, calcel, videos, clickPlay
        };
    },
}
</script>
<style>
.containers {
    width: 100%;
    height: 100%;
}

.cardContainer {
    width: 100%;
    height: 94vh;
    display: flex;
    flex-wrap: wrap;
    /* 允许自动换行 */
    justify-content: flex-start;
    /* 元素靠左对齐 */
    align-items: flex-start;
    /* 元素顶部对齐 */
}

.item {
    width: 300px;
    flex: 1 0 auto;
    /* 让元素自适应大小 */
    margin: 5px;
    /* 设置元素之间的间距 */
    background: #f2f2f2;
    padding: 10px;
    box-sizing: border-box;
    /* 包含 padding 在内的盒模型 */
}
</style>